import { DemoBlock } from '@/components/demos-util';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useNavigate } from 'alita';

import { UseAuthModel } from '@/models/useAuthModel';
import { useModel } from 'alita';
import {
  DetailResult,
  PageResult,
  Study,
  WeiXinUser,
  type StudySearchStatsXTagCount
} from '@/pages/types/type';

import {
  Avatar,
  Button,
  DotLoading,
  Ellipsis,
  Form,
  NavBar,
  Tag,
  Space,
  Result,
  Dialog,
} from 'antd-mobile';
import {
  BellOutline,
  CheckShieldOutline,
  FileOutline,
  RightOutline,
  SetOutline,
  SmileOutline,
  SoundOutline,
  TeamFill,
} from 'antd-mobile-icons';
import Toast, { ToastHandler } from 'antd-mobile/es/components/toast';
import { useEffect, useRef, useState } from 'react';
import './index.less';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
// import { UseAuthModel } from '@/models/useAuthModel';
const numberFormator = new Intl.NumberFormat();
// type Hospital = {
//   id: number;
//   name: string;
// };
// type DiagnosisGroup = {
//   id: number;
//   name: string;
// };
// type Department = {
//   errcode: number;
//   errmsg: string;
//   department: {
//     id: number;
//     name: string;
//     name_en: string;
//     department_leader: string;
//     parentid: number;
//     order: number;
//   };
// };

declare type HealthScreeningQuickHandleCount = {
  diagnosing: number;
  auditing: number;
}

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  //   const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);
  const [quickHandleCount, setQuickHandleCount] = useState<HealthScreeningQuickHandleCount>({ diagnosing: 0, auditing: 0 });

  const [statsXTagCount, setTatsXTagCount] =
    useState<StudySearchStatsXTagCount>({
      leader: undefined,
      userPerspective: 'xxx',
      wrapper: {
        clinicalDepartments: undefined,
        hospitals: undefined,
        grp1: undefined,
        grp2: undefined,
        doctor: undefined,
        projectManager: false,
      },
      countItems: [],
    });


  function getTabNumber() {
    const response2: Promise<Response> = fetch(
      `${urlPrefix}/api/study-search/stats-x-tag-count`,
      getRequestInit(),
    );
    response2.then((rsp: Response) => {
      if (rsp.ok) {
        rsp
          .json()
          .then(
            ({
              data,
              code,
              msg,
            }: {
              data?: StudySearchStatsXTagCount;
              code: number;
              msg: string;
            }) => {
              if (code === 0) {
                setTatsXTagCount(data!);
              }
            },
          );
      } else {
        Toast.show({ icon: 'fail', content: rsp.statusText });
      }
    });
  }

  function getHealthScreeningQuickHandleCount() {
    const response2: Promise<Response> = fetch(
      `${urlPrefix}/api/study-handle/get-health-screening-quick-handle-count`,
      getRequestInit(),
    );
    response2.then((rsp: Response) => {
      if (rsp.ok) {
        rsp
          .json()
          .then(
            ({
              data,
              code,
              msg,
            }: {
              data?: HealthScreeningQuickHandleCount;
              code: number;
              msg: string;
            }) => {
              if (code === 0) {
                setQuickHandleCount(data!);
              }
            },
          );
      } else {
        Toast.show({ icon: 'fail', content: rsp.statusText });
      }
    });
  }

  useEffect(() => {
    getHealthScreeningQuickHandleCount();
    getTabNumber();
  }, [])

  // 提交时状态控制
  // const [ing, setIng] = useState<boolean>();
  // const [fail, setFail] = useState<string>();
  // const [success, setSuccess] = useState<string>();
  // const [departments, setDepartments] = useState<Department[]>([]);
  // const [hospitals, setHospitals] = useState<Hospital[]>([]);
  // const [diagnosisGroups, setDiagnosisGroups] = useState<DiagnosisGroup[]>([]);

  const handler = useRef<ToastHandler>();

  type FieldModal = {
    deviceSerialNumber: string;
    meta: string;
  };
  const [form] = Form.useForm<FieldModal>();

  const model: UseAuthModel = useModel('useAuthModel');

  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `用户信息`,
        pageBackground: '#eee',
      },
    });

    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {

  }
  useEffect(load, [authOK]);
  function changUserBtn(e: any) {
    console.log(e);
  }



  if (tokening) {
    return <Result
      icon={<SmileOutline />}
      status='success'
      title='正在登录'
      description='正在获取你的信息...'
    />;
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }


  function checkBtn() {
    console.log('近期检查');
  }
  const { manageHospitals, diagnosisGroups, projectManager, doctor } = model.userInfo;
  return (
    <Page>
      <Content>
        <div className="infoUser" style={{ padding: '10px' }}>
          <div className="userLeft">
            <div className="userImg">
              <Avatar src={model.userInfo.avatar} style={{ '--border-radius': '50%' }} />
            </div>
            <div className="userMsg">
              <div className="userName">
                <Space>{model.userInfo.name}
                  {diagnosisGroups.length > 0 && <Tag round color={'primary'}>专家</Tag>}
                  {manageHospitals.length > 0 && <Tag color={'primary'}>医院管理</Tag>}
                  {projectManager && <Tag color={'primary'}>系统管理</Tag>}
                  {doctor && <Tag color={'primary'}>检查医生</Tag>}
                </Space>
              </div>

              {doctor && <div className="userPost">
                <span className="infoLabel">工号:</span>
                <span className="infoValue">{doctor.code}</span>
              </div>}

              {diagnosisGroups.length > 0 && <div className="userPost">
                <span className="infoLabel">职称:</span>
                <span className="infoValue">{'----'}</span>
              </div>}

            </div>
          </div>
          <div className="userRight">
            <div onClick={changUserBtn} className="editUserInfo">
              <span style={{ color: '#909399', fontSize: '14px' }}>
                编辑资料
              </span>
              <span style={{ fontWeight: 'bold' }}>
                <RightOutline />
              </span>
            </div>
          </div>
        </div>



        <div className="infoTab">
          <div className="infoStatistics">
            {statsXTagCount.countItems.map(({ tab, count, color }) => {
              return (<div className="countBG" key={tab.value} onClick={() => {
                navigate(`/study/search?xTag=${tab.value}`);
              }}>
                <div style={{
                  'color': `var(--adm-badge-color, var(--adm-color-${count <= 0 ? 'weak' : color === 'default' ? 'success' : color
                    }))`,
                }} >{count}</div>
                <div className="infoLabel">{tab.label}</div>
              </div>)
            })}
          </div>
          {(doctor || (diagnosisGroups && diagnosisGroups.length > 0)) && <div className="infoCheck" onClick={() => { }}>
            <div className="checkLeft">
              <div className="checkTitle">近期检查</div>
              <div className="checkBody">
                <div className="checkRow">
                  <div className="checkLabel">患者姓名:</div>
                  <div className="checkValue">{`张三`}</div>
                </div>
                <div className="checkRow">
                  <div className="checkLabel">申请单号:</div>
                  <div className="checkValue">
                    <Ellipsis direction="end" content={`1101101101010`} />
                  </div>
                </div>
                <div
                  className="checkRow"
                  style={{ justifyContent: 'space-between' }}
                >
                  <div style={{ width: '50%' }}>
                    <span className="checkLabel">年龄:</span>
                    <span className="checkValue">{`14`}</span>
                  </div>
                  <div style={{ width: '50%' }}>
                    <span className="checkLabel">性别:</span>
                    <span className="checkValue">{`女`}</span>
                  </div>
                </div>
                <div className="checkRow">
                  <div className="checkLabel" style={{ width: '65px' }}>
                    心电图诊断:
                  </div>
                  <div className="checkValue">
                    <Ellipsis
                      direction="end"
                      content={`1就阿斯利康大家啊三菱电机啊山卡拉登记啊收垃圾`}
                    />
                  </div>
                </div>
              </div>
            </div>
            <div className="checkRight">
              <div className="checkTitle">签名</div>
              <div className="checkBody">
                {`--------`}
              </div>
            </div>
          </div>}

        </div>
        <div className="infoGroup">

          {diagnosisGroups && diagnosisGroups.length > 0 && <> <div className="groupRow" onClick={() =>
            Dialog.confirm({
              confirmText: '批量报告',
              cancelText:'放弃',
              content: `确定要批量撰写${quickHandleCount.diagnosing}宗诊断报告吗？`,
              onConfirm: async () => {
                const url = '/api/study-batch-job-handle/crate-batch-job';
                let detailUrlResponse: Promise<Response> = fetch(
                  `${urlPrefix}${url}`,
                  postRequestInit({ maxCount: 10000, workingMode: 'healthScreening',jobType:'diagnosis' }),
                );
                detailUrlResponse
                  .then(async (rsp: Response) => {
                    if (rsp.ok) {
                      await rsp
                        .json()
                        .then(async ({ code, msg }: DetailResult<any>) => {
                          if (code === 0) {
                            Toast.show({
                              icon: 'success',
                              content: msg,
                            });
                          } else {
                            Toast.show({
                              icon: 'fail',
                              content: msg,
                            });
                          }
                        })
                        .catch((reason) => {
                          console.log(`提交批处理任务出错：${reason}`);
                        })
                        .finally(() => {
                        });
                    } else {
                      Toast.show({
                        icon: 'fail',
                        content: rsp.statusText,
                      });
                    }
                  })
                  .catch((reason: any) => {
                    console.error(reason);
                  })
                  .finally(() => {
                    console.log(`${url} outter finally!`);
                  });
              },
            })
          }>
            <div className="groupIcon">
              <BellOutline color='var(--adm-color-danger)' />
            </div>
            <div className="groupItem">
              <div>体检初筛正常待报告</div>
              <div>
                <span>
                  {quickHandleCount.diagnosing}
                </span>
                <RightOutline style={{ marginLeft: '10px' }} />
              </div>
            </div>
          </div>
            <div className="groupRow" onClick={() =>
              Dialog.confirm({
                confirmText: '批量审核',
                cancelText:'放弃',
                content: `确定要批量审核${quickHandleCount.auditing}宗诊断报告吗？`,
                onConfirm: async () => {
                  const url = '/api/study-batch-job-handle/crate-batch-job';
                  let detailUrlResponse: Promise<Response> = fetch(
                    `${urlPrefix}${url}`,
                    postRequestInit({ maxCount: 10000, workingMode: 'healthScreening' ,jobType:'audit'}),
                  );
                  detailUrlResponse
                    .then(async (rsp: Response) => {
                      if (rsp.ok) {
                        await rsp
                          .json()
                          .then(async ({ code, msg }: DetailResult<any>) => {
                            if (code === 0) {
                              Toast.show({
                                icon: 'success',
                                content: msg,
                              });
                            } else {
                              Toast.show({
                                icon: 'fail',
                                content: msg,
                              });
                            }
                          })
                          .catch((reason) => {
                            console.log(`提交批处理任务出错：${reason}`);
                          })
                          .finally(() => {
                          });
                      } else {
                        Toast.show({
                          icon: 'fail',
                          content: rsp.statusText,
                        });
                      }
                    })
                    .catch((reason: any) => {
                      console.error(reason);
                    })
                    .finally(() => {
                      console.log(`${url} outter finally!`);
                    });
                },
              })
            }>
              <div className="groupIcon">
                <SoundOutline color='var(--adm-color-danger)' />
              </div>
              <div className="groupItem">
                <div>体检报告正常待审核</div>
                <div>
                  <span>
                    {quickHandleCount.auditing}
                  </span>
                  <RightOutline style={{ marginLeft: '10px' }} />
                </div>
              </div>

            </div></>}

          {diagnosisGroups && (diagnosisGroups.reduce((unique, item) => {
            if (!unique.some(obj => obj.id === item.id)) {
              unique.push(item);
            }
            return unique;
          }, [])).map((dg, index) => {
            return (<div className="groupRow" key={dg.id} onClick={changUserBtn}>
              <div className="groupIcon">
                <TeamFill />
              </div>
              <div className="groupItem">
                <div>诊断组-{index + 1}</div>
                <div>
                  <span>
                    {dg.name}
                  </span>
                  <RightOutline style={{ marginLeft: '10px' }} />
                </div>
              </div>
            </div>);
          })}

          {manageHospitals && manageHospitals.length > 0 && manageHospitals.map(({ id, name }, index) => {
            return (<div className="groupRow" key={id} onClick={changUserBtn}>
              <div className="groupIcon">
                <TeamFill />
              </div>
              <div className="groupItem">
                <div>医院-{index + 1}</div>
                <div>
                  <span>
                    {name}
                  </span>
                  <RightOutline style={{ marginLeft: '10px' }} />
                </div>
              </div>
            </div>);
          })}

          {/* <div className="groupRow" onClick={changUserBtn}>
            <div className="groupIcon">
              <CheckShieldOutline />
            </div>
            <div className="groupItem">
              <div>设备</div>
              <div>
                <span>{`1号心电图机`}</span>
                <RightOutline style={{ marginLeft: '10px' }} />
              </div>
            </div>
          </div>
          <div className="groupRow" onClick={changUserBtn}>
            <div className="groupIcon">
              <FileOutline />
            </div>
            <div className="groupItem">
              <div>日志</div>
              <div>
                <span>{``}</span>
                <RightOutline style={{ marginLeft: '10px' }} />
              </div>
            </div>
          </div>
          <div className="groupRow" onClick={changUserBtn}>
            <div className="groupIcon">
              <SetOutline />
            </div>
            <div className="groupItem">
              <div>设置</div>
              <div>
                <span>{``}</span>
                <RightOutline style={{ marginLeft: '10px' }} />
              </div>
            </div>
          </div> */}
        </div>
        <div
          style={{
            width: '100%',
            position: 'absolute',
            bottom: '20px',
            padding: '0 20px',
          }}
        >
          <Button block color={'warning'} size="large">
            退出登录
          </Button>
        </div>
      </Content>
    </Page>
  );
};
